$(document).ready(function() {
	reloadTree();
	loadUserTable();
	$('#reset').click();
	layui.use('form', function() {
		var form = layui.form;

		form.on('select(FileType)', function(data) {
			console.log(data);
			FileType = data.value;
			loadUserTable()
		});
		//监听提交
		form.on('submit(formDemo)', function(data) {
			let params = new FormData();
			console.log("hahahah");

			params.append('name', data.field.realname);
			params.append('type', data.field.fileType);
			params.append('projectId', projectId);

			if ($('#filePath')[0].files[0]) {
				params.append('file', $('#filePath')[0].files[0]);
			}
			addUser(params)
			return false;
		});
	});
})

var projectId = '';
var FileType = "";
var isPar = true;
var isProject = '';
var operate;
//工地表格
function loadUserTable() {
	layui.use('table', function() {
		var table = layui.table;

		//第一个实例
		table.render({
			title: '',
			text: {
				none: '暂无数据'
			},
			elem: '#main-right-table',
			skin: 'nob',
			url: ajaxPrefix() + '/manage/file/list',
			headers: {
				SessionId: localStorage.getItem('sessionId')
			},
			where: {
				pageSize: 10,
				projectId: projectId,
				fileType: FileType
			},
			parseData: function(res) { //res 即为原始返回的数据
				console.log(res);
				return {
					"code": res.status == 200 ? 0 : 1, //解析接口状态
					"msg": res.message, //解析提示文本
					"count": res.result.total, //解析数据长度
					"data": res.result.data //解析数据列表
				};
			},
			request: {
				pageName: 'pageNum', //页码的参数名称，默认：page
				limitName: 'pageSize' //每页数据量的参数名，默认：limit
			},
			page: {
				limit: 10,
			} //开启分页
			,
			cols: [
				[ //表头
					{
						field: 'projectName',
						title: '所属工地',
						align: 'center'
					},
					{
						field: 'name',
						title: '文件名',
						align: 'center'
					}, {
						field: 'fileType',
						title: '文件类型',
						align: 'center',
					}, {
						field: 'updateTime',
						title: '上传时间',
						templet: function(d) {
							return d.updateTime == undefined ? '暂无' : d.updateTime.substring(0,
								19)
						},
						align: 'center'
					}, {
						title: '操作',
						align: 'center',
						width: 120,
						templet: function(d) {
							return `<a style="color:#54A1F1" href="/images/` + d.filePath +
								`" download="/images/` + d.filePath + `">下载</a>`
						},
					},
				]
			]
		});
		layui.use('form', function() {
			var form = layui.form;
			table.on('rowDouble(table-click)', function(obj) {
				operate = obj.data.id;
				$(":password").removeAttr('required');
				$(":password").removeAttr('lay-verify');
				$('.add-user>.main-tit>label').html('修改');
				let data = obj.data;

				form.val("formTest", {
					"realname": data.realname,
					"gender": data.gender == '男' ? 2 : 1,
					"roleId": data.roleId,
					"idNumber": data.idnumber,
					"password": data.password,
					"cellphone": data.cellphone,
				});
				$('.add-user').show();
			});
		});
	});
}



showDetail = (res) => {

	$('.detail').show();
}




showMenu = (res) => {

	$('.main-left-nav').toggle();
	$('.main-left-tree').toggle();

}




/*树*/
var setting = {
	async: {
		autoParam: ["id"],
		enable: true,
		url: getAsyncUrl,
		type: "get",
		dataFilter: ajaxDataFilter,
		headers: {
			"SessionId": localStorage.getItem('sessionId')
		},
	},
	view: {
		expandSpeed: "fast",
		fontCss: getFont,
		showLine: true,
		dblClickExpand: false,
		showIcon: false
	},
	callback: {
		onAsyncSuccess: zTreeOnAsyncSuccess,
		onClick: zTreeOnClick,
		beforeExpand: beforeExpand,
		onExpand: onExpand
	},
	data: {
		key: {
			title: "name"
		},
		simpleData: {
			enable: true,
			idKey: "code",
			pIdKey: "parentCode"
		}
	}
};

var zNodes;

function reloadTree() {
	zTree = $.fn.zTree.init($("#treeDemo"), setting);
}

function getAsyncUrl(treeId, treeNode) {
	if (!treeNode) {
		url = ajaxPrefix() + "/area/projecttree?areaCode=" + 320113;
	} else {
		url = ajaxPrefix() + "/area/projecttree?areaCode=" + treeNode.id;
	}

	return url;
}
//异步数据过滤
function ajaxDataFilter(treeId, parentNode, childNodes) {

	return childNodes;
}

//异步加载成功
function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
	if (!treeNode) { //根节点
		var rootNode = zTree.getNodesByParam("level", 0)[0];
		return;
	}

	var selTreeId = _selTreeId;
	if (!!selTreeId) {
		var selNode = zTree.getNodeByParam("id", selTreeId);
		if (!!selNode) {
			_selTreeId = null;
			zTree.selectNode(selNode);
			zTreeOnClick();
		}
	}
}
//获取选中的节点
function getSelectedNode() {
	var treeNode = zTree.getSelectedNodes();
	if (treeNode.length == 0) {

		return false;
	}
	return treeNode[0];
}

//刷新子节点并确定要选中节点ID
var _selTreeId = null;

function reloadNode(refreshId, isParent, selTreeId) {
	var node = zTree.getNodeByParam("id", refreshId);
	if (!!node && !!isParent) {
		node = node.getParentNode();
		if (!node) {
			_selTreeId = selTreeId;
			reloadTree();
			return;
		}
	}
	if (!!node) {
		_selTreeId = selTreeId;
		zTree.reAsyncChildNodes(node, "refresh");
	}
}


//右击事件
function getFont(treeId, node) {
	return node.font ? node.font : {};
}
//仅能打开一个子节点
var curExpandNode = null;

function beforeExpand(treeId, treeNode) {
	var pNode = curExpandNode ? curExpandNode.getParentNode() : null;
	var treeNodeP = treeNode.parentTId ? treeNode.getParentNode() : null;
	for (var i = 0, l = !treeNodeP ? 0 : treeNodeP.children.length; i < l; i++) {
		if (treeNode !== treeNodeP.children[i]) {
			zTree.expandNode(treeNodeP.children[i], false);
		}
	}
	while (pNode) {
		if (pNode === treeNode) {
			break;
		}
		pNode = pNode.getParentNode();
	}
	if (!pNode) {
		singlePath(treeNode);
	}

}

function singlePath(newNode) {
	if (newNode === curExpandNode) return;
	if (curExpandNode && curExpandNode.open == true) {
		var zTree = $.fn.zTree.getZTreeObj("treeDemo");
		if (newNode.parentTId === curExpandNode.parentTId) {
			zTree.expandNode(curExpandNode, false);
		} else {
			var newParents = [];
			while (newNode) {
				newNode = newNode.getParentNode();
				if (newNode === curExpandNode) {
					newParents = null;
					break;
				} else if (newNode) {
					newParents.push(newNode);
				}
			}
			if (newParents != null) {
				var oldNode = curExpandNode;
				var oldParents = [];
				while (oldNode) {
					oldNode = oldNode.getParentNode();
					if (oldNode) {
						oldParents.push(oldNode);
					}
				}
				if (newParents.length > 0) {
					zTree.expandNode(oldParents[Math.abs(oldParents.length - newParents.length) - 1], false);
				} else {
					zTree.expandNode(oldParents[oldParents.length - 1], false);
				}
			}
		}
	}
	curExpandNode = newNode;
}

function onExpand(event, treeId, treeNode) {
	curExpandNode = treeNode;
}

//单击树节点事件
function zTreeOnClick(event, treeId, treeNode) {

	isPar = treeNode.isParent;
	isProject = treeNode.type;
	if (!treeNode.isParent) {
		projectId = treeNode.code;
		loadUserTable();
	}
}


$('div.search-button').click(function() {
	if (isPar || isProject == "area") {
		layer.msg('请先在右侧选择所属工地')
	} else {
		$(":password").attr('required', true);
		$(":password").attr('lay-verify', 'required');
		operate = true;
		$('.add-user>.main-tit>label').html('新增');
		$('.add-user').show();
	}

})
$(".add-user>.main-tit>div").click(function() {
	$('.add-user').hide();
	$('#reset').click();
})
/*新增用户*/
addUser = (params) => {
	$.ajax({
		url: ajaxPrefix() + '/manage/file/add',
		type: 'post',
		data: params,
		dataType: "json",
		beforeSend: function(XMLHttpRequest) {
			XMLHttpRequest.setRequestHeader("SessionId", localStorage.getItem('sessionId'));
		},
		cache: false,
		processData: false,
		contentType: false,
		// "Content-Type":"application/json"
		success: function(res) {
			if (res.status == 200) {
				layer.msg('新增成功', {
					time: 1000
				});
				$(".add-site>.main-tit>div").click();
				loadUserTable();
			} else {
				layer.msg('操作失败！', {
					time: 1000
				})
			}

		}
	});

}


function changename(files) {
	console.log(files.files[0].name);
	// $('.upload-image').attr('value', $('.file-input').val());
	let file = files.files[0];
	if (file) {
		$('.upFileName').text(file.name);
		// var reader = new FileReader();
		// reader.onload = function(evt) {
		// }
		// reader.readAsDataURL(file);
	}
}